# controllers/user_auth.py
from functools import wraps
from flask import request, make_response, session, redirect, url_for, render_template, current_app
from models.database import SessionLocal
from models.user import User
from werkzeug.security import check_password_hash, generate_password_hash
from datetime import datetime

def requires_role(required_role):
    """角色权限装饰器"""
    def decorator(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            # 检查用户是否已登录
            if 'user_id' not in session:
                return redirect(url_for('login'))
            
            # 检查是否为环境变量中的超级管理员账户（ID为0）
            if session['user_id'] == 0:
                # 创建一个临时的root用户对象
                class TempUser:
                    def __init__(self):
                        self.id = 0
                        self.username = current_app.config.get('ADMIN_USERNAME', 'admin')
                        self.role = "root"
                        self.country = None
                    
                    def has_permission(self, required_role, target_country=None):
                        return True
                        
                    def can_view_order(self, order_country):
                        return True
                        
                    def can_view_customer(self, customer_country):
                        return True
                        
                    def can_add_order(self):
                        return True
                        
                    def can_add_customer(self):
                        return True
                
                # 将用户对象添加到请求上下文
                request.current_user = TempUser()
                return f(*args, **kwargs)
            
            db = SessionLocal()
            try:
                user = db.query(User).filter(User.id == session['user_id'], User.is_active == True).first()
                if not user:
                    session.clear()
                    return redirect(url_for('login'))
                
                # 检查角色权限
                role_hierarchy = {
                    "user": 1,
                    "manager": 2,
                    "root": 3
                }
                
                user_role_level = role_hierarchy.get(user.role, 0)
                required_role_level = role_hierarchy.get(required_role, 0)
                
                if user_role_level < required_role_level:
                    return "权限不足", 403
                    
                # 将用户对象添加到请求上下文
                request.current_user = user
                return f(*args, **kwargs)
            finally:
                db.close()
        return decorated
    return decorator

def requires_auth(f):
    """基本认证装饰器（保持向后兼容）"""
    @wraps(f)
    def decorated(*args, **kwargs):
        # 首先检查会话认证
        if 'user_id' in session:
            # 检查是否为环境变量中的超级管理员账户（ID为0）
            if session['user_id'] == 0:
                # 创建一个临时的root用户对象
                class TempUser:
                    def __init__(self):
                        self.id = 0
                        self.username = current_app.config.get('ADMIN_USERNAME', 'admin')
                        self.role = "root"
                        self.country = None
                    
                    def has_permission(self, required_role, target_country=None):
                        return True
                        
                    def can_view_order(self, order_country):
                        return True
                        
                    def can_view_customer(self, customer_country):
                        return True
                        
                    def can_add_order(self):
                        return True
                        
                    def can_add_customer(self):
                        return True
                
                request.current_user = TempUser()
                return f(*args, **kwargs)
            
            db = SessionLocal()
            try:
                user = db.query(User).filter(User.id == session['user_id'], User.is_active == True).first()
                if user:
                    request.current_user = user
                    return f(*args, **kwargs)
            finally:
                db.close()
        
        # 如果会话认证失败，回退到基本认证
        auth = request.authorization
        if auth:
            # 检查是否为默认管理员账户
            username = current_app.config.get('ADMIN_USERNAME', 'admin')
            password = current_app.config.get('ADMIN_PASSWORD', 'admin')
            
            if auth.username == username and auth.password == password:
                # 创建一个临时的root用户对象
                class TempUser:
                    def __init__(self):
                        self.id = 0
                        self.username = username
                        self.role = "root"
                        self.country = None
                    
                    def has_permission(self, required_role, target_country=None):
                        return True
                        
                    def can_view_order(self, order_country):
                        return True
                        
                    def can_view_customer(self, customer_country):
                        return True
                        
                    def can_add_order(self):
                        return True
                        
                    def can_add_customer(self):
                        return True
                
                request.current_user = TempUser()
                return f(*args, **kwargs)
        
        # 要求认证
        resp = make_response('Login required', 401)
        resp.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
        return resp
    return decorated

def hash_password(password):
    """密码哈希函数"""
    return generate_password_hash(password)

def verify_password(plain_password, hashed_password):
    """验证密码"""
    return check_password_hash(hashed_password, plain_password)

def authenticate_user(username, password):
    """用户认证验证（不设置session）"""
    # 首先检查是否为环境变量中的超级管理员账户
    admin_username = current_app.config.get('ADMIN_USERNAME', 'admin')
    admin_password = current_app.config.get('ADMIN_PASSWORD', 'admin')
    
    if username == admin_username and password == admin_password:
        # 创建一个临时的root用户对象
        class TempUser:
            def __init__(self):
                self.id = 0
                self.username = username
                self.role = "root"
                self.country = None
                self.is_active = True
            
            def has_permission(self, required_role, target_country=None):
                return True
                
            def can_view_order(self, order_country):
                return True
                
            def can_view_customer(self, customer_country):
                return True
                
            def can_add_order(self):
                return True
                
            def can_add_customer(self):
                return True
        
        return TempUser()
    
    # 如果不是超级管理员，则从数据库验证
    db = SessionLocal()
    try:
        user = db.query(User).filter(User.username == username, User.is_active == True).first()
        if user and verify_password(password, user.password_hash):
            return user
        return None
    finally:
        db.close()